package com.ygqh.baby.handler;

import com.ygqh.baby.ao.FileType;
import com.ygqh.baby.ao.SalesPlatform;
import com.ygqh.baby.exception.YgException;
import com.ygqh.baby.model.ShareProductImageReq;
import com.ygqh.baby.model.YgProductImagesModel;
import com.ygqh.baby.model.YgProductModel;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.FileService;
import com.ygqh.baby.service.WxSmallAuthorityService;
import com.ygqh.baby.service.YgProductService;
import com.ygqh.baby.service.YgUserService;
import com.ygqh.baby.utils.ImageUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.awt.*;
import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: sunshuo
 * @Date: 2019/6/17/017 11:34
 * @Version: 1.0
 */
@Component
public class ShareImageHandler {

    @Autowired
    private RedisDao redisDao;
    @Autowired
    private YgProductService ygProductService;
    @Autowired
    private FileService fileService;
    @Autowired
    private WxSmallAuthorityService wxSmallAuthorityService;
    @Autowired
    private YgUserService ygUserService;

    @Value("${image.domain}")
    private String domain;
    @Value("${image.upload.temp.url}")
    private String tempDir;

    /**
     * 分享商品图
     *
     * @param imageReq imageReq
     * @return
     */
    public List<String> shareProduct(ShareProductImageReq imageReq) throws Exception {
        String key = imageReq.getRedisKey();
        /*// 从缓存中读取商品分享图
        String imageUrl = redisDao.get(key);
        if (StringUtils.isNotBlank(imageUrl)) {
            return JSON.parseArray(imageUrl, String.class);
        }*/
        // 获取商品信息
        YgProductModel product = ygProductService.findDetailModelForYjdian(imageReq.getProductId());
        if (product == null) {
            throw new RuntimeException("系统异常，请刷新页面重试");
        }
        // 获取所有的商品图（包括商品图和详情图，第一个为主图）
        List<String> imageList = getProductImageList(product);
        if (CollectionUtils.isEmpty(imageList)) {
            throw new RuntimeException("抱歉，该商品暂无图片");
        }
        // 最终目标图临时文件地址
        String tempTargetImagePath = tempDir + key + ".jpg";
        // 分享商品图文件地址
        String tempSrcImagePath = getShareProductDitu();
        // 印制基础相关信息
        generateBaseInfo(tempTargetImagePath, tempSrcImagePath, imageReq.getHeadMessage(), imageReq.getFootMessage());
        tempSrcImagePath = tempTargetImagePath;
        // 印制商品相关信息
        generateProductInfo(tempTargetImagePath, tempSrcImagePath, product, imageList.get(0), imageReq.getTargetPrice(),
                imageReq.getPriceMessage(), imageReq.getPricePrefix());
        tempSrcImagePath = tempTargetImagePath;
        // 印制用户相关信息
        generateShareUserInfo(tempTargetImagePath, tempSrcImagePath, imageReq.getShareUserId());
        tempSrcImagePath = tempTargetImagePath;
        // 印制落地页二维码
        generateSmallQrcode(tempTargetImagePath, tempSrcImagePath, key, imageReq);
        File file = new File(tempTargetImagePath);
        String codeUrl = fileService.uploadImage(file, FileType.Temp, true);
        codeUrl = replaceToHttpsUrl(codeUrl);
        imageList.set(0, codeUrl);
        /*redisDao.set(key, JSON.toJSONString(imageList), 5 * 60 * 1000);*/
        return imageList;
    }

    /**
     * 获取商品所有相关图
     *
     * @param product 商品信息
     * @return
     */
    private List<String> getProductImageList(YgProductModel product) {
        List<String> imageList = new ArrayList<>();
        for (YgProductImagesModel image : product.getProductImages()) {
            String imagePath = image.getImagePath();
            if (StringUtils.isBlank(imagePath)) {
                continue;
            }
            if (image.getIsMain()) {
                imageList.add(0, replaceToHttpsUrl(imagePath));
            } else {
                imageList.add(replaceToHttpsUrl(imagePath));
            }
        }
        String detailImagePath = product.getDetailImagePath();
        if (StringUtils.isNotBlank(detailImagePath)) {
            for (String dip : detailImagePath.split(",")) {
                if (StringUtils.isNotBlank(dip)) {
                    imageList.add(replaceToHttpsUrl(dip));
                }
            }
        }
        return imageList;
    }

    /**
     * 印制基础相关信息
     *
     * @param tempTargetImagePath   目标图临时文件
     * @param tempSrcImagePath      底图临时文件
     * @param headMessage           首行信息
     * @param footMessage           尾部信息
     */
    private void generateBaseInfo(String tempTargetImagePath, String tempSrcImagePath, String headMessage,
                                  String footMessage) {
        if (StringUtils.isNotBlank(headMessage)) {
            int fontSize = 30;
            if (headMessage.length() >= 13) {
                double rate = (headMessage.length() - 13);
                rate = rate / headMessage.length() * 28;
                fontSize = (int) (fontSize - rate);
            }
            ImageUtils.pressText(headMessage, tempSrcImagePath, tempTargetImagePath,
                    "微软雅黑", 20, Color.black, fontSize, 165, 315, 1.0f);
        }
        if (StringUtils.isNotBlank(footMessage)) {
            int fontSize = 24;
            if (footMessage.length() >= 9) {
                int rate = (headMessage.length() - 9) / 5;
                fontSize = fontSize - rate;
            }
            tempSrcImagePath = tempTargetImagePath;
            ImageUtils.pressText(footMessage, tempSrcImagePath, tempTargetImagePath,
                    "微软雅黑", 20, Color.gray, fontSize, 490, 1255, 1.0f);
        }
    }

    /**
     * 印制商品分享小程序码
     *
     * @param tempTargetImagePath   目标图临时文件
     * @param tempSrcImagePath      底图临时文件
     * @param prefixKey             前缀KEY
     * @param imageReq             imageReq
     */
    private void generateSmallQrcode(String tempTargetImagePath, String tempSrcImagePath, String prefixKey,
                                     ShareProductImageReq imageReq) {
        // 小程序码
        /*String key = prefixKey + "_wxacode";
        String smallQrcode = redisDao.get(key);
        if (StringUtils.isBlank(smallQrcode)) {
            *//*smallQrcode = "http://yiigoo-tmp.oss-cn-shanghai.aliyuncs.com/qrcode/2019/06/17/1560751171604506047.jpg";*//*
            smallQrcode = wxSmallAuthorityService.getSamllQrcode(imageReq.getFloorPage(), 1, imageReq.getPlatformNo());
            redisDao.set(key, smallQrcode, 0);
        }*/
        String smallQrcode = wxSmallAuthorityService.getSamllQrcode(imageReq.getFloorPage(), 1, imageReq.getPlatformNo());
        if (StringUtils.isBlank(smallQrcode)) {
            throw new YgException("生成小程序码异常");
        }
        ImageUtils.pressImageMark(smallQrcode, tempSrcImagePath, tempTargetImagePath,
                498, 1063, 1.0f, 165, 165);
    }

    /**
     * 印制用户圆形头像
     *
     * @param tempTargetImagePath   目标图临时文件
     * @param tempSrcImagePath      底图临时文件
     * @param shareUserId           分享用户id
     */
    private void generateShareUserInfo(String tempTargetImagePath, String tempSrcImagePath, Long shareUserId) {
        // 用户头像
        String press = tempDir + shareUserId + "_headImage.jpg";
        YgUser shareUser = ygUserService.findById(shareUserId);
        // 生成圆形头像
        try {
            ImageUtils.makeCircularImgByUrl(shareUser.getHeadImageUrl(), press);
        } catch (Exception e) {
            throw new YgException("用户头像过期或错误", e);
        }
        ImageUtils.pressImageMark2(press, tempSrcImagePath, tempTargetImagePath,
                600, 265, 1.0f, 80, 80);
    }

    /**
     * 印制商品相关信息
     *
     * @param tempTargetImagePath   目标图临时文件
     * @param tempSrcImagePath      底图临时文件
     * @param product               商品信息
     * @param productMainImage      指定商品图
     * @param targetPrice           商品目标价格
     * @param priceMessage          商品价格标题
     * @param pricePrefix          商品价格前缀
     */
    private void generateProductInfo(String tempTargetImagePath, String tempSrcImagePath, YgProductModel product,
                                     String productMainImage, BigDecimal targetPrice, String priceMessage,
                                     String pricePrefix) {
        productMainImage = replaceImageUrl(productMainImage);
        if (StringUtils.isBlank(productMainImage)) {
            throw new RuntimeException("抱歉，分享主图链接异常");
        }
        ImageUtils.pressImageMark(productMainImage, tempSrcImagePath, tempTargetImagePath,
                78, 360, 1.0f, 600, 600);
        tempSrcImagePath = tempTargetImagePath;
        // 印制商品名称
        String productName = product.getProductName();
        // 去掉销售标识
        int index = productName.indexOf("】");
        if (index != -1) {
            productName = productName.substring(index + 1);
        }
        // 商品名称长度超过20时，分两行显示
        String productNameByFirst;
        String productNameBySecond = null;
        if (productName.length() > 20) {
            productNameByFirst = productName.substring(0, 20);
            productNameBySecond = productName.substring(20, productName.length() > 40 ? 40 : productName.length());
        } else {
            productNameByFirst = productName;
        }
        int y = 1050;
        ImageUtils.pressText(productNameByFirst, tempSrcImagePath, tempTargetImagePath,
                "微软雅黑", 20, Color.black, 30, 90, y, 1.0f);
        tempSrcImagePath = tempTargetImagePath;
        if (StringUtils.isNotBlank(productNameBySecond)) {
            y += 40;
            ImageUtils.pressText(productNameBySecond, tempSrcImagePath, tempTargetImagePath,
                    "微软雅黑", 20, Color.black, 30, 90, y, 1.0f);
            tempSrcImagePath = tempTargetImagePath;
        }
        // 印制商品卖点
        String sellingPoint = product.getSellingPoint();
        if (StringUtils.isNotBlank(sellingPoint)) {
            if (sellingPoint.length() > 10) {
                sellingPoint = sellingPoint.substring(0, 10);
            }
            y += 40;
            ImageUtils.pressText(sellingPoint, tempSrcImagePath, tempTargetImagePath,
                    "微软雅黑", 20, Color.black, 30, 90, y, 1.0f);
            tempSrcImagePath = tempTargetImagePath;
        }
        // 印制商品价格、分享图类型
        BigDecimal couponPrice = ygProductService.getCouponPriceForNewCustom(SalesPlatform.Yijiadian);
        BigDecimal originalPrice;
        BigDecimal salePrice;
        String priceTitle;
        if (product.getPromotionPrice() != null && product.getPromotionPrice().compareTo(BigDecimal.ZERO) > 0) {
            originalPrice = product.getProductSalePrice();
            salePrice = product.getPromotionPrice();
            priceTitle = "拼团优惠价";
        } else {
            originalPrice = product.getProductSalePrice();
            salePrice = originalPrice.compareTo(couponPrice) < 0 ? originalPrice : originalPrice.subtract(couponPrice);
            priceTitle = "新人券后价";
        }
        if (StringUtils.isBlank(priceMessage)) {
            priceMessage = priceTitle;
        }
        if (targetPrice == null) {
            targetPrice = salePrice;
        }
        // 价格标题
        ImageUtils.pressText(priceMessage, tempSrcImagePath, tempTargetImagePath,
                "微软雅黑", 20, Color.white, 22, 98, 995, 1.0f);
        tempSrcImagePath = tempTargetImagePath;
        // 售价
        ImageUtils.pressText(pricePrefix + "￥" + targetPrice, tempSrcImagePath, tempTargetImagePath,
                "微软雅黑", 20, Color.white, 28, 102, 1230, 1.0f);
        tempSrcImagePath = tempTargetImagePath;
        // 原价
        ImageUtils.pressText("￥" + originalPrice, tempSrcImagePath, tempTargetImagePath,
                "微软雅黑", 20, Color.white, 26, 320, 1230, 1.0f);
        tempSrcImagePath = tempTargetImagePath;
        // 原价过期白线
        ImageUtils.pressText("————", tempSrcImagePath, tempTargetImagePath,
                "微软雅黑", 20, Color.white, 26, 320, 1230, 1.0f);
    }

    /**
     * 商品分享底图
     *
     * @return
     */
    private String getShareProductDitu() {
        String fileName = "yijiadian_product_share_ditu_v20190617.jpg";
        // 底图阿里云路径
        String sourceUrl = domain + "default/" + fileName;
        // 本地路径
        String localPath = tempDir + "/" + fileName;
        File localFile = ImageUtils.getFile(localPath);
        if (!localFile.exists()) {
            ImageUtils.saveImageToDisk(sourceUrl, tempDir, fileName);
        }
        return localPath;
    }

    private String replaceToHttpsUrl(String imageUrl) {
        if (StringUtils.isBlank(imageUrl)) {
            return null;
        }
        return imageUrl.replace("http://img.yiigoo.com", "https://yiigoo-pro.oss-cn-beijing.aliyuncs.com");
    }

    private String replaceImageUrl(String imageUrl) {
        if (StringUtils.isBlank(imageUrl)) {
            return null;
        }
        int index = imageUrl.lastIndexOf(".");
        if (index == -1) {
            return null;
        }
        return imageUrl.substring(0, index) + "-800*800" + imageUrl.substring(index);
    }
}
